package com.monster.util;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.IOException;
import java.util.Random;

/**
 * 工具类，用于生成、发送验证码
 * @author cyb
 */
public class UserMessageUtil {
    /**
     * 向指定的手机号发送指定信息
     * @param smsMob 接收验证码的手机号
     * @param smsText 验证码文本信息
     */
    public static void sendMessage(String smsMob, String smsText) {
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod("http://gbk.sms.webchinese.cn");
        post.addRequestHeader("Content-Type",
                "application/x-www-form-urlencoded;charset=gbk");// 在头文件中设置转码
        NameValuePair[] data = { new NameValuePair("Uid", "sileigong"), //  登录的用户名
                new NameValuePair("Key", "d41d8cd98f00b204e980"),//  接口安全密钥
                new NameValuePair("smsMob", smsMob), // 接受验证码的手机号
                new NameValuePair("smsText", smsText) };  //  验证码
        post.setRequestBody(data);
        try {
            client.executeMethod(post);
            String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Header[] headers = post.getResponseHeaders();
        int statusCode = post.getStatusCode();
        post.releaseConnection();
        /*System.out.println("statusCode:" + statusCode);
        for (Header h : headers) {
            System.out.println(h.toString());
        }
        System.out.println(result); // 打印返回消息状态*/
    }

    /**
     * 获得6位数的随机验证码
     * @return 6位数验证码
     */
    public static String getRandomCode() {
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++) {
            code += random.nextInt(10) + "";
        }
        return code;
    }


}
